<?php

namespace App\Models;

use App\Http\Controllers\WXBizDataCrypt;
use Tymon\JWTAuth\Contracts\JWTSubject;
use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User as Authenticatable;

class User extends Authenticatable implements JWTSubject    # 这里别忘了加
{
    use Notifiable;

    // Rest omitted for brevity

    /**
     * Get the identifier that will be stored in the subject claim of the JWT.
     *
     * @return mixed
     */
    public function getJWTIdentifier()
    {
        return $this->getKey();
    }

    /**
     * Return a key value array, containing any custom claims to be added to the JWT.
     *
     * @return array
     */
    public function getJWTCustomClaims()
    {
        return [];
    }

    static function wxLogin($code,$encryptedData,$iv)
    {
        $appId = config('weChart.AppID');
        $appSecret = config('weChart.AppSecret');
        $apiUrl = 'https://api.weixin.qq.com/sns/jscode2session';
        $api_url = $apiUrl . '?appid=' . $appId . '&secret=' . $appSecret . '&js_code=' . $code . '&grant_type=authorization_code';
        $result = file_get_contents($api_url);
        $result = json_decode($result,true);
        $openid = $result['openid'];
        $session_key = $result['session_key'];
        //更新用户信息
        $userphone = self::getUserPhone($appId,$session_key,$encryptedData,$iv);
        $userphone = json_decode($userphone,true);
        if (!$userphone){
            return false;
        }
        $user = self::where('openid',$openid)->first();
        $user_nickname = 'CCF_'.rand_name();
        $user_headimgurl = config('weChart.default_img');
        if (!$user){
            $user = new User();
            $user->openid = $result['openid'];
            $user->user_nickname = $user_nickname;
            $user->user_headimgurl = $user_headimgurl;
            $user->save();
        }
        return $user;
    }

    static function getUserPhone($appid,$sessionKey,$encryptedData,$iv){
        $pc = new WXBizDataCrypt($appid, $sessionKey);
        $errCode = $pc->decryptData($encryptedData, $iv, $data );
        if ($errCode == 0) {
            return $data;
        } else {
            return false;
        }
    }

}
